<?php

if(!defined('IN_DISCUZ')) {
    exit('Access Denied');
}
global $_G;
$uid = $_G['uid'];
// $http = 'http://account-center.cn';
$http = 'https://user.20idc.com';

// 获取表模型
$table_connfig = C::t('#erling_account_center#er_account_config');
$table_connfig_data = $table_connfig->fetch_by_keys(['appid','redirect_url']);
$appid = $table_connfig_data['appid']['value'];
$domain = $table_connfig_data['redirect_url']['value'];
$redirect_url = $domain.'/plugin.php?id=erling_account_center:redirect_callback';
// echo '<pre>';
// print_r($table_connfig_data);
// echo '</pre>';

$table_user = C::t('#erling_account_center#er_account_user');

// 用户的聚合登录账号信息
$er_account_user_info = $table_user->fetch_by_uid($uid);

// 查询绑定数据是否存在，不存在指向注册或绑定已有账号

if(!$er_account_user_info) {
    // 生成随机值 state
    $state = md5(uniqid(mt_rand(), true));

    // 构建请求数据，采用get传递，type=register_bind/bind，// register_bind表示先注册聚合账号然后来直接绑定，bind直接登录后使用登录账号绑定当前网站
    $get = 'domain='.$domain.'&appid='.$appid.'&redirect_url='.$redirect_url.'&response_type=code&scope=get_user_info&state='.$state;
    $html_register = $http.'/authorize/register?type=register_bind'.$get;
    $html_bind = $http.'/authorize/login?type=bind&'.$get;
    
} else {
    // 如果存在
    $access_token = $er_account_user_info['access_token'];

    // 通过 api/authorize/get/user-info 获取信息，access_token
    $post_url = $http.'/api/authorize/get/user-info';
    $post_data = array(
        'access_token' => $access_token,
    );

    // 发送POST请求获取用户信息
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $post_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 添加以下两行禁用SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $account_center_data = json_decode($response, true);

    // 如果获取信息返回 access_token 401 已过期，需要重新登录
    $html_login = $http.'/authorize/login?type=login&'.$get;//（暂时不用）

}


// include template('')




